package com.zzyl.serve.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;

import com.zzyl.serve.domain.*;
import com.zzyl.serve.dto.NursingTaskDto;
import com.zzyl.serve.dto.TaskDto;
import com.zzyl.serve.mapper.ElderMapper;
import com.zzyl.serve.mapper.NursingElderMapper;
import com.zzyl.serve.mapper.NursingTaskMapper;
import com.zzyl.serve.service.*;
import com.zzyl.serve.util.IDCardUtils;
import com.zzyl.serve.vo.NursingNameVo;
import com.zzyl.serve.vo.NursingPlanVo;
import com.zzyl.serve.vo.NursingProjectPlanVo;
import com.zzyl.serve.vo.NursingTaskVo;
import com.zzyl.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 护理任务Service业务层处理
 *
 * @author howstrong
 * @date 2024-09-27
 */
@Service
@Slf4j
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {
    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    @Autowired
    private ElderMapper elderMapper;

    /**
     * 取消任务
     *
     * @param taskDto
     * @return
     */
    @Override
    public int cancelTask(TaskDto taskDto) {
        //查询护理任务
        NursingTask nursingTask = getById(taskDto.getTaskId());
        //修改任务
        if (ObjectUtil.isEmpty(nursingTask)) {
            throw new BaseException("护理任务不存在");
        }

        //修改状态
        nursingTask.setStatus(3);
        nursingTask.setCancelReason(taskDto.getReason());
        boolean updated = updateById(nursingTask);
        return updated ? 1 : 0;
    }

    /**
     * 任务改期
     *
     * @param taskDto
     * @return
     */
    @Override
    public int rescheduleTask(TaskDto taskDto) {
        //查询护理任务
        NursingTask nursingTask = getById(taskDto.getTaskId());
        //修改任务
        if (ObjectUtil.isEmpty(nursingTask)) {
            throw new BaseException("护理任务不存在");
        }

        //修改执行时间
        nursingTask.setEstimatedServerTime(taskDto.getEstimatedServerTime());
        boolean updated = updateById(nursingTask);
        return updated ? 1 : 0;
    }

    /**
     * 执行任务
     *
     * @param taskDto
     * @return
     */
    @Override
    public int executeTask(TaskDto taskDto) {
        //查询护理任务
        NursingTask nursingTask = getById(taskDto.getTaskId());
        //修改任务
        if (ObjectUtil.isEmpty(nursingTask)) {
            throw new BaseException("护理任务不存在");
        }
        nursingTask.setStatus(2);
        nursingTask.setRealServerTime(taskDto.getEstimatedServerTime());
        nursingTask.setTaskImage(taskDto.getTaskImage());
        nursingTask.setMark(taskDto.getMark());

        boolean updated = updateById(nursingTask);
        return updated ? 1 : 0;
    }

    @Autowired
    private ISysUserService userService;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskVo selectNursingTaskById(Long id) {
        /**
         * 查询护理任务返回的值对象(nursingTaskVo)涉及多张表的数据
         * 护理任务表、查询入住表、护理员老人关联表、老人表、用户表
         */
        // 1. 根据护理任务id从护理任务表中查询护理任务
        NursingTask nursingTask = getById(id);
        // 2. 将nursingTask对象(护理任务表中的信息)拷贝到nursingTaskVo中
        NursingTaskVo nursingTaskVo = BeanUtil.toBean(nursingTask, NursingTaskVo.class);

        // 获取护理等级名称
        // 3. 根据从护理任务表中查到的老人id从入住表中查询入住信息
        CheckIn checkIn = checkInService.getOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, nursingTask.getElderId()));
        // 4. 将入住信息中的护理等级名称赋值到nursingTaskVo中
        nursingTaskVo.setNursingLevelName(checkIn.getNursingLevelName());

        //获取护理员昵称
        // 5. 根据护理任务表中查到的老人id从护理员老人关联表中查询护理员昵称
        List<SysUser> sysUsers = nursingElderMapper.selectUserByElderId(nursingTask.getElderId());
        List<String> list = sysUsers.stream().map(sysUser -> sysUser.getNickName()).collect(Collectors.toList());
        // 6. 将护理员昵称赋值到nursingTaskVo中
        nursingTaskVo.setNursingName(list);

        //获得年龄
        // 6. 根据从护理任务表中查到的老人id从老人表中查询老人详细信息
        Elder elder = elderMapper.selectById(nursingTask.getElderId());
        // 7. 将根据老人身份证号计算年龄并赋值到nursingTaskVo中
        nursingTaskVo.setAge(IDCardUtils.getAgeByIdCard(elder.getIdCardNo()));

        //性别
        // 8. 将根据老人身份证号计算性别并赋值到nursingTaskVo中
        nursingTaskVo.setSex(elder.getSex() == 0 ? "女" : "男");

        //获取执行人或取消人
        // 9. 判断护理任务是否更新, 如果更新, 则获取更新人id
        if (StringUtils.isNotEmpty(nursingTask.getUpdateBy())) {
            // 10. 根据更新人id从用户表中查询更新人昵称
            SysUser sysUser = userService.selectUserById(Long.valueOf(nursingTask.getUpdateBy()));
            // 11. 将更新人昵称赋值到nursingTaskVo中
            nursingTaskVo.setUpdater(sysUser.getNickName());
        }
        // 12. 返回NursingTaskVo对象
        return nursingTaskVo;
    }

    @Autowired
    private NursingElderMapper nursingElderMapper;

    @Autowired
    private INursingProjectService nursingProjectService;

    /**
     * 查询护理任务列表
     *
     * @param nursingTaskDto 护理任务
     * @return 护理任务
     */
    @Override
    public TableDataInfo selectNursingTaskList(NursingTaskDto nursingTaskDto) {
        // 1. 设置分页查询参数
        PageHelper.startPage(nursingTaskDto.getPageNum(), nursingTaskDto.getPageSize());
        // 2. 获取分页对象
        List<NursingTask> nursingTasks = nursingTaskMapper.selectByPage(nursingTaskDto);
        Page<NursingTask> page = (Page<NursingTask>) nursingTasks;
        // 3. 获取全部护理任务的List集合
        List<NursingTask> records = page.getResult();
        /**
         * 根据接口文档, 响应数据格式为护理任务详细信息的集合, 且每个护理任务要包含护理员的昵称集合
         * 相较于上面分页查询返回的NursingTask, 要求返回的响应数据格式多出了(类型为List<String>的)NursingName字段信息
         * 由于没有创建一个新的NursingTaskVo类用于返回响应数据, 而使用NursingTask集合
         * 由于数据库中的nursing_task表中没有nursing_Name的字段,
         * 因此在NursingTask类中增加了(一个查询时无需映射到数据库, 类型为List<String>的)nursingName字段, 用于存储护理员昵称集合
         * 由于nursing_task表中有nursing_id字段, 而没有nursing_name字段, 需要通过nursing_id字段查询护理员的昵称NursingName
         */
        // 4. 由于护理员和护理任务是多对多关系 ,创建一个存储护理员id的set集合, 用于去重
        Set<Long> userIds = new HashSet<>();
        // 5. 遍历每一个护理任务, 将护理任务的护理员id添加到userIds集合中
        nursingTasks.forEach(nursingTask -> {
            // 6. 如果护理员id不为空, 说明此时有护理员, 需要将护理员id添加到userIds集合中
            if (StringUtils.isNotEmpty(nursingTask.getNursingId())) {
                // 7. 由于nursing_task表中nursing_id列是多个id组成的字符串, 需要将其拆分, 并进行类型转换
                String[] split = nursingTask.getNursingId().split(",");
                // 8. 遍历每一个id, 将其转换为Long类型, 并添加到userIds集合中
                for (String nid : split) {
                    userIds.add(Long.valueOf(nid));
                }
            }
        });
        // 9. 如果护理任务为空或者护理员列表为空, 说明此时没有护理任务, 直接返回空的查询结果
        if (CollUtil.isEmpty(nursingTasks) || CollUtil.isEmpty(userIds)) {
            return getTableDataInfo(page, records);
        }
        // 10. 如果有护理任务且护理任务已分配护理员, 通过nursing_id从老人护理员中间表查询老人-护理员键值集合
        List<NursingNameVo> nursingNameVoList = nursingElderMapper.selectNickNameByNursingId(userIds);
        // 11. 根据老人id对所有老人-护理员键值对象进行分组, 以便获取每个老人对应的所有护理员昵称
        Map<Long, List<NursingNameVo>> listMap = nursingNameVoList.stream().collect(Collectors.groupingBy(NursingNameVo::getElderId));
        // 12. 遍历每一个护理任务, 根据老人id将护理员昵称添加到nursingTask护理任务中
        records.forEach(nursingTask -> {
            // 13. 根据老人id查询老人-护理员键值集合获取对应的老人-护理员键值集合
            List<NursingNameVo> nursingNameVos = listMap.get(nursingTask.getElderId());
            // 14. 将老人-护理员键值集合转换为护理员昵称集合
            List<String> nursingNameStrList = nursingNameVos.stream().map(NursingNameVo::getNursingName).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(nursingNameStrList)) {
                // 15. 将护理员昵称集合添加到nursingTask中
                nursingTask.setNursingName(nursingNameStrList);
            }
        });
        // 16. 返回查询结果
        return getTableDataInfo(page, records);
    }

    private TableDataInfo getTableDataInfo(Page page, List<NursingTask> records) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setMsg("请求成功");
        tableDataInfo.setCode(200);
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(records);
        return tableDataInfo;
    }


    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    @Autowired
    private INursingLevelService nursingLevelService;

    @Autowired
    private INursingPlanService nursingPlanService;

    @Autowired
    private INursingElderService nursingElderService;

    /**
     * 生成护理任务
     *
     * @param elder
     */
    @Override
    public void createMonthTask(Elder elder) {
        //校验
        if (elder == null || elder.getId() == null) {
            log.info("老人不能为空");
            return;
        }

        //获取入住信息
        CheckIn checkIn = checkInService.getOne(Wrappers.<CheckIn>lambdaQuery().eq(CheckIn::getElderId, elder.getId()));

        //获取入住及入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.getOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        //开始时间
        LocalDateTime startTime = LocalDateTime.now();
        //判断开始是在当天时间
        if (checkInConfig.getFeeStartDate().toLocalDate().isEqual(LocalDateTime.now().toLocalDate())) {
            startTime = checkInConfig.getFeeStartDate();
        }

        //护理等级
        NursingLevel nursingLevel = nursingLevelService.selectNursingLevelById(checkInConfig.getNursingLevelId());
        //护理计划
        NursingPlanVo nursingPlanVo = nursingPlanService.selectNursingPlanById(nursingLevel.getLplanId());
        //查询老人对应的护理员列表
        List<NursingElder> nursingElderList = nursingElderService.list(Wrappers.<NursingElder>lambdaQuery().eq(NursingElder::getElderId, elder.getId()));
        String nursingIds;
        if (CollUtil.isNotEmpty(nursingElderList)) {
            List<Long> list = nursingElderList.stream().map(NursingElder::getNursingId).collect(Collectors.toList());
            //多个id用逗号分隔，转换为字符串
            nursingIds = StringUtils.join(list, ",");
        } else {
            nursingIds = "";
        }

        //查询所有的护理项目
        List<NursingProject> list = nursingProjectService.list();
        //转换为map key是id,value是name
        Map<Long, String> nursingProjectMap = list.stream().collect(Collectors.toMap(NursingProject::getId, NursingProject::getName));

        //组装护理任务
        List<NursingTask> nursingTasks = new ArrayList<>();

        LocalDateTime finalStartTime = startTime;
        nursingPlanVo.getProjectPlans().forEach(v -> {
            //执行频次
            Integer executeFrequency = v.getExecuteFrequency();
            //执行时间
            String executeTime = v.getExecuteTime();
            LocalTime localTime = LocalTime.parse(executeTime);
            //开始执行时间
            LocalDateTime firstExecutionTime = LocalDateTime.of(finalStartTime.toLocalDate(), localTime);
            // 计算相差天数
            LocalDateTime monthEndTime = LocalDateTime.of(finalStartTime.getYear(), checkInConfig.getFeeStartDate().getMonth(), finalStartTime.toLocalDate().lengthOfMonth(), 23, 59);
            // 间隔天数
            long diffDays = monthEndTime.toLocalDate().toEpochDay() - finalStartTime.toLocalDate().toEpochDay() + 1;
            if (v.getExecuteCycle().equals(0)) {
                // 日
                createTaskByDay(firstExecutionTime, diffDays, nursingTasks, executeFrequency, elder, v, nursingIds, nursingProjectMap);
            } else if (v.getExecuteCycle().equals(1)) {
                // 周
                createTaskByWeek(firstExecutionTime, diffDays, nursingTasks, executeFrequency, elder, v, monthEndTime, nursingIds, nursingProjectMap);
            } else {
                // 月
                createTaskByMonth(firstExecutionTime, monthEndTime, nursingTasks, executeFrequency, elder, v, nursingIds, nursingProjectMap);
            }
        });

        if (CollUtil.isEmpty(nursingTasks)) {
            return;
        }
        saveBatch(nursingTasks);
    }

    /**
     * 按月创建任务
     *
     * @param firstExecutionTime
     * @param monthEndTime
     * @param nursingTasks
     * @param executeFrequency
     * @param elder
     * @param v
     */
    private void createTaskByMonth(LocalDateTime firstExecutionTime, LocalDateTime monthEndTime, List<NursingTask> nursingTasks, Integer executeFrequency, Elder elder, NursingProjectPlanVo v, String nursingIds, Map<Long, String> nursingProjectMap) {
        LocalDateTime executionTime = firstExecutionTime;
        Integer diffDay = (monthEndTime.plusSeconds(1).getDayOfMonth() - executionTime.getDayOfMonth()) / executeFrequency;
        for (int x = 0; x < executeFrequency; x++) {
            // 根据时间差和执行顺序计算每个任务的具体时间
            LocalDateTime seconds = executionTime.plusDays(diffDay * x);
            // 初始化护理任务对象
            NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
            // 将生成的任务添加到任务列表中
            nursingTasks.add(nursingTask);
        }
    }

    /**
     * 根据周为单位创建护理任务
     * <p>
     * 此方法旨在根据给定的开始时间、差异天数、执行频率等参数，为指定的老人生成护理任务列表
     * 它考虑了跨年情况以及每月结束时间的限制，避免生成越过月末的有效任务
     *
     * @param firstExecutionTime 首次执行时间，用于计算后续任务的时间点
     * @param diffDays           任务之间的时间差，以天为单位，此方法专注于周级别，故此值应与7的倍数有关
     * @param nursingTasks       护理任务列表，方法将新生成的任务添加到此列表中
     * @param executeFrequency   执行频率，决定每周内任务执行的次数
     * @param elder              老人信息对象，任务相关的老人信息由此对象提供
     * @param v                  护理项目计划的视图对象，包含项目ID等信息
     * @param monthEndTime       每月结束时间的限制，确保任务不会跨月生成
     * @param nursingIds         护理员ID列表，以字符串形式传递，用于分配任务给护理员
     */
    private void createTaskByWeek(LocalDateTime firstExecutionTime, long diffDays, List<NursingTask> nursingTasks, Integer executeFrequency, Elder elder, NursingProjectPlanVo v, LocalDateTime monthEndTime, String nursingIds, Map<Long, String> nursingProjectMap) {
        int i;
        // 以7天为步长遍历差异天数，创建每周的任务
        for (i = 0; i < diffDays - 7; i = i + 7) {
            // 计算每周结束时间
            LocalDateTime dayEndTime = LocalDateTime.of(firstExecutionTime.plusDays(i + 7).toLocalDate(), LocalTime.of(23, 59));
            // 计算本周的执行起始时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 根据执行频率计算时间差，用于确定本周内各任务的时间点
            Integer diffDay = (dayEndTime.plusSeconds(1).getDayOfYear() - executionTime.getDayOfYear()) / executeFrequency;
            // 根据执行频率生成本周的任务
            for (int x = 0; x < executeFrequency; x++) {
                // 根据时间差和执行顺序计算每个任务的具体时间
                LocalDateTime seconds = executionTime.plusDays(diffDay * x);
                // 初始化护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }

        // 处理边界情况，当i超过diffDays-7且小于diffDays时
        if (i > diffDays - 7 && i < diffDays) {
            // 计算到达diffDays时的结束时间
            LocalDateTime dayEndTime = LocalDateTime.of(firstExecutionTime.plusDays(i + 7).toLocalDate(), LocalTime.of(23, 59));
            // 如果结束时间与开始时间年份不同，则返回，避免跨年任务
            if (ObjectUtil.notEqual(dayEndTime.getYear(), firstExecutionTime.getYear())) {
                return;
            }
            // 计算执行时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 计算时间差，确定任务时间点
            Integer diffDay = (dayEndTime.plusSeconds(1).getDayOfYear() - executionTime.getDayOfYear()) / executeFrequency;
            // 根据执行频率生成任务，直到月末
            for (int x = 0; x < executeFrequency; x++) {
                // 计算每个任务的时间
                LocalDateTime seconds = executionTime.plusDays(diffDay * x);
                // 如果任务时间超过月末结束时间，则停止生成
                if (seconds.isAfter(monthEndTime)) {
                    break;
                }
                // 初始化护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }

    }


    /**
     * 按日创建任务
     * @param firstExecutionTime
     * @param diffDays
     * @param nursingTasks
     * @param executeFrequency
     * @param elder
     * @param v
     */
    /**
     * 根据天数创建护理任务
     * <p>
     * 该方法根据首次执行时间、任务间隔天数、护理任务列表、执行频率、老人信息和护理项目计划数据，
     * 创建一系列的护理任务。任务的创建以天为单位，直到达到任务间隔天数为止。
     *
     * @param firstExecutionTime 首次执行时间，标志着任务创建的起始时间
     * @param diffDays           任务间隔天数，确定需要创建任务的天数范围
     * @param nursingTasks       护理任务列表，创建的任务将被添加到此列表中
     * @param executeFrequency   执行频率，决定一天内任务执行的次数
     * @param elder              老人对象，包含执行任务的老人的信息
     * @param v                  护理项目计划数据对象，包含护理项目的相关信息
     */
    private void createTaskByDay(LocalDateTime firstExecutionTime, long diffDays, List<NursingTask> nursingTasks, Integer executeFrequency, Elder elder, NursingProjectPlanVo v, String nursingIds, Map<Long, String> nursingProjectMap) {
        // 遍历每一天，从首次执行时间开始，直到达到任务间隔天数
        for (int i = 0; i < diffDays; i++) {
            // 计算每一天的任务执行起始时间
            LocalDateTime executionTime = firstExecutionTime.plusDays(i);
            // 确定当天任务执行的结束时间（当天的23:59）
            LocalDateTime dayEndTime = LocalDateTime.of(executionTime.toLocalDate(), LocalTime.of(23, 59));
            // 计算当天内每次执行任务之间的小时差，用于确定执行时间点
            Integer diffHour = (dayEndTime.plusSeconds(1).getHour() - executionTime.getHour()) / executeFrequency;
            // 根据执行频率创建任务
            for (int x = 0; x < executeFrequency; x++) {
                // 计算每个任务的具体执行时间
                LocalDateTime seconds = executionTime.plusHours(diffHour * x);
                // 创建新的护理任务对象
                NursingTask nursingTask = getNursingTask(elder, v, nursingIds, seconds, nursingProjectMap);
                // 将生成的任务添加到任务列表中
                nursingTasks.add(nursingTask);
            }
        }
    }

    /**
     * 获取护理任务对象
     *
     * @param elder
     * @param v
     * @param nursingIds
     * @param seconds
     * @return
     */
    private NursingTask getNursingTask(Elder elder, NursingProjectPlanVo v, String nursingIds, LocalDateTime seconds, Map<Long, String> nursingProjectMap) {
        NursingTask nursingTask = new NursingTask();
        // 设置任务状态
        nursingTask.setStatus(1);
        // 设置护理员ID列表
        nursingTask.setNursingId(nursingIds);
        // 老人姓名
        nursingTask.setElderName(elder.getName());
        // 设置床位号
        nursingTask.setBedNumber(elder.getBedNumber());
        // 设置预估服务时间
        nursingTask.setEstimatedServerTime(seconds);
        // 设置项目ID
        nursingTask.setProjectId(Long.valueOf(v.getProjectId()));
        // 设置老人ID
        nursingTask.setElderId(elder.getId());
        //匹配护理项目
        nursingTask.setProjectName(nursingProjectMap.get(nursingTask.getProjectId()));

        return nursingTask;
    }
}
